package tvv.levelup.configuration;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 * Created by Server on 08.09.14.
 */
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "tvv.levelup")
@Configuration
public class JpaConfiguration {

    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource =
                new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");
        return driverManagerDataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {

        HibernateJpaVendorAdapter ha = new HibernateJpaVendorAdapter();

        ha.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean emb =
                new LocalContainerEntityManagerFactoryBean();

        emb.setJpaVendorAdapter(ha);
        emb.setDataSource(dataSource());
        emb.setPackagesToScan("tvv.levelup");
        emb.afterPropertiesSet();
        return emb.getObject();
    }

    @Bean
    public EntityManager entityManager(EntityManagerFactory factory){
        return factory.createEntityManager();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager jpaTransactionManager =
                new JpaTransactionManager();
        return jpaTransactionManager;
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }
}
